<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <lb-table
      :column="tableData.column"
      :data="tableData.data"
      border
      :height="550"
      pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 40, 60, 80]"
      :pager-count="5"
      :current-page.sync="currentPage"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
    >
    </lb-table>
    <component
      :is="modelName"
      :id="id"
      :visible.sync="show"
      @close="close"
    ></component>
  </lb-layout>
</template>

<script>
import auth from "@/plugins/auth";
import { getroomList, deleteRoom } from "@/api/park/roommsg.js";
import { getparkList } from "@/api/park/parkmsg.js";
import { getbuildingList } from "@/api/park/buildingmsg.js";
import { getfloorList } from "@/api/park/floormsg.js";
import { getroomTypeList } from "@/api/park/roomType.js";
import { deepClone, dealElectricity, saveQuery, outQuery } from "@/utils/index";

import operate from "@/views/configuration/park/roommsg/components/operate.vue";
export default {
  name: "",
  components: {
    operate,
  },
  dicts: ["room_direction", "special_energy_consumption_type"],
  data() {
    return {
      //弹窗
      id: "",
      modelName: "",
      show: false,
      parkList: [],
      buildingList: [],
      floorList: [],
      roomTypeList: [],
      apsForm: {
        formRef: "form",
        labelWidth: "auto",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            parkId: {
              label: "区域名称:",
              render: (h) => {
                let that = this;
                let arr = [...that.parkList];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().parkId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择区域",
                        value: valNum,
                        clearable: true,
                        filterable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("parkId", value);
                          that.$refs?.form?.setFieldValue("buildingId", null);
                          that.$refs?.form?.setFieldValue("floorId", null);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            buildingId: {
              label: "楼宇名称:",
              render: (h) => {
                let that = this;
                let arr = [...that.buildingList];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().buildingId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择楼宇",
                        value: valNum,
                        clearable: true,
                        filterable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("buildingId", value);
                          that.$refs?.form?.setFieldValue("floorId", null);
                          that.$forceUpdate();
                        },
                        "visible-change": (value) => {
                          if (value) {
                            that.requestBuildinglist();
                          }
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            floorId: {
              label: "楼层名称:",
              render: (h) => {
                let that = this;
                let arr = [...that.floorList];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().floorId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择楼层",
                        value: valNum,
                        clearable: true,
                        filterable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("floorId", value);
                          that.$forceUpdate();
                        },
                        "visible-change": (value) => {
                          if (value) {
                            that.requestFloorList();
                          }
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            roomType: {
              label: "房间类型:",
              render: (h) => {
                let that = this;
                let arr = [...that.roomTypeList];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().roomType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择房间类型",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("roomType", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            specialEnergyFlag: {
              label: "用能类型:",
              render: (h) => {
                let that = this;
                let arr = [...this.dict.type.special_energy_consumption_type];
                // 数据严谨处理,处理后端数据异常情况
                let valNum =
                  that.$refs?.form?.getFieldsValue().specialEnergyFlag;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择用能类型",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "specialEnergyFlag",
                            value
                          );
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            name: {
              label: "房间号:",
              typeName: "el-input",
              placeholder: "请输入房间号",
            },
            nickname: {
              label: "房间名称:",
              typeName: "el-input",
              placeholder: "请输入房间名称",
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            {
              label: "新增",
              type: "primary",
              typeName: "el-button",
              display: true,
              plain: true,
              size: "small",
              icon: "el-icon-plus",
              click: () => this.showModel("operate"),
            },
          ],
        },
      },
      currentPage: 1,
      pageSize: 20,
      total: 0,
      tableData: {
        column: [
          {
            prop: "parkName",
            label: "区域名称",
            minWidth: 120,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "buildingName",
            label: "楼宇名称",
            minWidth: 120,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "floorName",
            label: "楼层名称",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "roomTypeName",
            label: "房间类型",
            minWidth: 120,
            align: "center",
            showOverflowTooltip: true,
          },

          {
            prop: "name",
            label: "房间号",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "nickname",
            label: "房间名称",
            minWidth: 120,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "roomArea",
            label: "房间面积",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let unit = "㎡";
              let area = scope.row.roomArea ?? 0;
              area = dealElectricity(area, 100, 2);
              let a = area + unit;
              return <div>{a}</div>;
            },
          },
          {
            prop: "direction",
            label: "房间朝向",
            minWidth: 80,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.room_direction}
                    value={scope.row.direction}
                  />
                </div>
              );
            },
          },
          {
            prop: "usedDeptName",
            label: "使用部门",
            minWidth: 120,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "specialEnergyFlag",
            label: "用能类型",
            minWidth: 120,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.special_energy_consumption_type}
                    value={scope.row.specialEnergyFlag}
                  />
                </div>
              );
            },
          },
          {
            prop: "shared",
            label: "是否公摊",
            minWidth: 80,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let text = scope.row.shared == 1 ? "是" : "否";
              return <div>{text}</div>;
            },
          },
          {
            prop: "remarks",
            label: "备注",
            align: "center",
            showOverflowTooltip: true,
          },
          {
            label: "操作",
            width: 220,
            fixed: "right",
            render: (h, scope) => {
              let that = this;
              let a = (
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-user"
                  v-hasPermi={[
                    "parkManage:roomUser:config",
                    "parkManage:room:detail",
                    "parkManage:energyDevice:config",
                  ]}
                  onClick={() => {
                    let obj = {
                      parkId: that.$refs?.form?.getFieldsValue().parkId,
                      buildingId: that.$refs?.form?.getFieldsValue().buildingId,
                      floorId: that.$refs?.form?.getFieldsValue().floorId,
                      roomType: that.$refs?.form?.getFieldsValue().roomType,
                      specialEnergyFlag:
                        that.$refs?.form?.getFieldsValue().specialEnergyFlag,
                      name: that.$refs?.form?.getFieldsValue().name,
                      nickname: that.$refs?.form?.getFieldsValue().nickname,
                    };
                    saveQuery("roommsgsticssearchQuery", obj);
                    that.$router.push({
                      path: "/resource/park/roomUser",
                      query: { id: scope.row.id },
                    });
                  }}
                >
                  配置
                </el-button>
              );
              let b = (
                <el-button
                  v-hasPermi={["parkManage:room:edit"]}
                  type="text"
                  size="small"
                  icon="el-icon-edit"
                  onClick={() => {
                    that.showModel("operate", scope.row);
                  }}
                >
                  编辑
                </el-button>
              );
              let c = (
                <el-button
                  v-hasPermi={["parkManage:room:remove"]}
                  type="text"
                  size="small"
                  icon="el-icon-delete"
                  onClick={() => {
                    that.handlerDelete(scope.row);
                  }}
                  class="text-danger"
                >
                  删除
                </el-button>
              );
              return (
                <div>
                  {a}
                  {b}
                  {c}
                </div>
              );
            },
          },
        ],
        data: [],
      },
      fromRouter: "",
    };
  },
  created() {
    this.requestParklist();
    this.requestBuildinglist();
    this.requestFloorList();
    this.requestroomTypelist();
  },
  mounted() {
    this.judgePermi();
    this.handlerSearchDetail();
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.fromRouter = from?.path ?? "";
    });
  },
  methods: {
    judgePermi() {
      if (auth.hasPermi("parkManage:room:add")) {
        this.apsForm.formConfig.formSoltButton[2].display = false;
      }
    },
    // 园区集合
    requestParklist() {
      this.parkList = [];
      getparkList({})
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.rows ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item?.name ?? "",
                value: item?.id,
              };
              this.parkList.push(obj);
            });
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!401001");
        });
    },
    // 楼宇集合
    requestBuildinglist() {
      this.buildingList = [];
      let params = {};
      let parkId = this.$refs?.form?.getFieldsValue().parkId;
      if (String(parkId).length > 0) {
        params.parkId = parkId;
      }
      getbuildingList(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.rows ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item?.name ?? "",
                value: item?.id,
              };
              this.buildingList.push(obj);
            });
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!402001");
        });
    },
    // 楼层集合
    requestFloorList() {
      this.floorList = [];
      let params = {};
      let parkId = this.$refs?.form?.getFieldsValue().parkId;
      let buildingId = this.$refs?.form?.getFieldsValue().buildingId;
      if (String(parkId).length > 0) {
        params.parkId = parkId;
      }
      if (String(buildingId).length > 0) {
        params.buildingId = buildingId;
      }
      getfloorList(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.rows ?? [];
          console.log(arr, "floorlist");
          if (arr.length > 0) {
            arr.map((item) => {
              let floorName = item?.name ?? "";
              let buildingName = item?.buildingName ?? "";
              let obj = {
                label: buildingName + "-" + floorName,
                value: item?.id,
              };
              this.floorList.push(obj);
            });
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!403001");
        });
    },
    // 房间类型
    requestroomTypelist() {
      this.roomTypeList = [];
      getroomTypeList({})
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.rows ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item?.name ?? "",
                value: item?.id,
              };
              this.roomTypeList.push(obj);
            });
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!304001");
        });
    },
    async initData(data) {
      let that = this;
      let query = {
        ...data,
      };
      query.pageNum = that.currentPage;
      query.pageSize = that.pageSize;
      that.$store.commit("app/updateApiCount", "add");
      await getroomList(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res?.rows ?? [];
          that.total = res?.total ?? 0;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 搜索
    handlerSearchDetail() {
      let form = {
        ...outQuery("roommsgsticssearchQuery", this.fromRouter, [
          "/resource/park/roomUser",
        ]),
      };
      if (Object.keys(form).length > 0) {
        this.$refs?.form?.setFieldValue("parkId", form?.parkId ?? null);
        this.$refs?.form?.setFieldValue("buildingId", form?.buildingId ?? null);
        this.$refs?.form?.setFieldValue("floorId", form?.floorId ?? null);
        this.$refs?.form?.setFieldValue("roomType", form?.roomType ?? null);
        this.$refs?.form?.setFieldValue(
          "specialEnergyFlag",
          form?.specialEnergyFlag ?? null
        );
        this.$refs?.form?.setFieldValue("name", form?.name ?? "");
        this.$refs?.form?.setFieldValue("nickname", form?.nickname ?? "");
      }
      const { ...other } = this.$refs?.form?.getFieldsValue();
      const data = {
        ...other,
      };
      this.initData(data);
    },
    // 重置
    handleReset() {
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    handlerDelete(row) {
      let that = this;
      let id = row.id;
      const text = "是否确认删除" + (row?.name ?? "该条数据") + "？";
      this.$modal
        .confirm(text)
        .then(() => {
          that.delectRequest(id);
        })
        .catch(() => {
          that.$message({
            message: "取消删除",
          });
        });
    },
    delectRequest(id) {
      let that = this;
      deleteRoom(id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          that.$message.success("已删除!");
          that.handlerSearchDetail();
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!403005");
        });
    },
    // 弹窗
    showModel(name, params) {
      this.modelName = name;
      this.id = params?.id || "";
      setTimeout(() => {
        this.show = true;
      }, 200);
    },
    close(status) {
      this.show = false;
      setTimeout(() => {
        if (status) this.handlerSearchDetail();
      }, 200);
    },
  },
};
</script>

<style lang="scss" scoped></style>
